package com.badlogic.androidgames.framework.impl;

import java.util.ArrayList;
import java.util.List;

import com.badlogic.androidgames.framework.Input.KeyEvent;
import com.badlogic.androidgames.framework.Pool;
import com.badlogic.androidgames.framework.Pool.PoolObjectFactory;

import android.view.View;
import android.view.View.OnKeyListener;
/**
 * @deprecated:键盘处理	Keyboard 键盘
 * @author frank
 * @date 2015年11月29日
 */
public class KeyboardHandler implements OnKeyListener {
	/**pressed 按下**/
	boolean[] pressedKeys = new boolean[128];
	/**Event 事件	Pool 池**/
	Pool<KeyEvent> keyEventPool;
	/**Buffer 缓冲**/
	List<KeyEvent> keyEventsBuffer = new ArrayList<KeyEvent>();
	List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
	
	public KeyboardHandler(View view) {
		PoolObjectFactory<KeyEvent> factory = new PoolObjectFactory<KeyEvent>() {
			@Override
			public KeyEvent createObject() {
				return new KeyEvent();
			}
		};
		keyEventPool = new Pool<KeyEvent>(factory, 100);
		view.setOnKeyListener(this);
		view.setFocusableInTouchMode(true);	// 触摸是否能获得焦点
		view.requestFocus();	// 请求焦点
	}
	
	@Override
	public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
		// ACTION_MULTIPLE 多点操作
		if (event.getAction() == android.view.KeyEvent.ACTION_MULTIPLE)
			return false;
		synchronized (this) {	// synchronized 同步
			KeyEvent keyEvent = keyEventPool.newObject();
			keyEvent.keyCode = keyCode;
			keyEvent.keyChar = (char) event.getUnicodeChar();	// 得到Unicode字符
			if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {	// 按下
				keyEvent.type = KeyEvent.KEY_DOWN;
				if (keyCode > 0 && keyCode < 127)
					pressedKeys[keyCode] = true;
			}
			if (event.getAction() == android.view.KeyEvent.ACTION_UP) {		// 松开
				keyEvent.type = KeyEvent.KEY_UP;
				if (keyCode > 0 && keyCode < 127)
					pressedKeys[keyCode] = false;
			}
			keyEventsBuffer.add(keyEvent);
		}
		return true;
	}
	/**判断是否按下**/
	public boolean isKeyPressed(int keyCode) {
		if (keyCode < 0 || keyCode > 127)
			return false;
		return pressedKeys[keyCode];
	}
	
	public List<KeyEvent> getKeyEvents() {
		synchronized (this) {
			int len = keyEvents.size();
			for (int i = 0; i < len; i++)
				keyEventPool.free(keyEvents.get(i));
			keyEvents.clear();
			keyEvents.addAll(keyEventsBuffer);
			keyEventsBuffer.clear();
			return keyEvents;
		}
	}
}
